package com.ruoyi.web.controller.eat;

import com.ruoyi.eat.domain.Order;
import com.ruoyi.eat.domain.OrderItem;
import com.ruoyi.eat.domain.GoodsSpu;
import com.ruoyi.eat.domain.UserAddress;
import com.ruoyi.eat.service.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SnowflakeIdWorker;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单Controller
 */
@Controller
@RequestMapping("/eat/order")
public class OrderController extends BaseController {
    private String prefix = "eat/order";

    @Autowired
    private IOrderService carOrderService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IGoodsSpuService goodsSpuService;
    @Autowired
    private IUserAddressService userAddressService;

    @GetMapping()
    public String order( ) {
        return prefix + "/order";
    }

    /**
     * 查询订单列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Order carOrder) {

        carOrder.setUserId(getUserId());

        startPage();
        List<Order> list = carOrderService.selectCarOrderList(carOrder);
        return getDataTable(list);
    }



    /**
     * 查看订单详情
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") String id, ModelMap mmap) {
        Order carOrder = carOrderService.selectCarOrderById(id);
        mmap.put("carOrder", carOrder);

        return prefix + "/detail";
    }



    /**
     * 新增订单
     */
    @GetMapping("/add/{id}")
    public String addSpu(@PathVariable("id") Long id, ModelMap mmap) {

        GoodsSpu goodsSpu = goodsSpuService.selectGoodsSpuById(id);
        GoodsSpu query = new GoodsSpu();
        query.setCreateBy(goodsSpu.getCreateBy());
        mmap.put("goodsList", goodsSpuService.selectGoodsSpuList(query));

        UserAddress queryAddress = new UserAddress();
        queryAddress.setUserId(getUserId() + "");
        List<UserAddress> userAddresses = userAddressService.selectUserAddressList(queryAddress);
        mmap.put("userAddresses", userAddresses);


        //初始化客户选择的商品
        Order carOrder = new Order();
        List<OrderItem> carOrderItemList = new ArrayList<>();
        OrderItem carOrderItem = new OrderItem();

        carOrderItem.setGoodId(id);
        carOrderItem.setGoodPrice(goodsSpu.getSalesPrice());
        carOrderItem.setGoodName(goodsSpu.getName());
        carOrderItem.setGoodAmount(1);
        carOrderItemList.add(carOrderItem);
        carOrder.setSalesPrice(goodsSpu.getSalesPrice());
        carOrder.setCarOrderItemList(carOrderItemList);
        mmap.put("carOrder", carOrder);
        mmap.put("goodsSpu", goodsSpu);
        return prefix + "/edit";
    }


    /**
     * 新建订单
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        Order carOrder = carOrderService.selectCarOrderById(id);
        mmap.put("carOrder", carOrder);
        mmap.put("userList", userService.selectUserListRange(getSysUser(), "01"));
        mmap.put("goodsList", goodsSpuService.selectGoodsSpuList(null));
        return prefix + "/edit";
    }

    /**
     * 修改保存订单
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Order carOrder) {

        UserAddress userAddress = userAddressService.selectUserAddressById(carOrder.getUserAddressId() + "");
        carOrder.setUserAddressName(userAddress.getUserName());
        carOrder.setProvinceName(userAddress.getProvinceName());
        carOrder.setCityName(userAddress.getCityName());
        carOrder.setCountyName(userAddress.getCountyName());
        carOrder.setDetailInfo(userAddress.getDetailInfo());
        carOrder.setTelNum(userAddress.getTelNum());


        carOrder.setUserId(getUserId());
        if (StringUtils.isEmpty(carOrder.getId())) {
            SysUser sysUser = userService.selectUserById(getUserId());
            carOrder.setId(sysUser.getPhonenumber() + "_" + SnowflakeIdWorker.generateId());

            return toAjax(carOrderService.insertCarOrder(carOrder));
        }

        return toAjax(carOrderService.updateCarOrder(carOrder, false));
    }

    /**
     * 删除订单
     */
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(carOrderService.deleteCarOrderByIds(ids));
    }

    /**
     * 订单收款
     */
    @Log(title = "订单收款", businessType = BusinessType.UPDATE)
    @PostMapping("/pay")
    @ResponseBody
    public AjaxResult pay(String id) {

        Order carOrder1 = carOrderService.selectCarOrderById(id);
        long create = carOrder1.getCreateTime().getTime();
        long now = new Date().getTime();
        if (now - create > 30 * 60 * 1000) {
            return error("订单已超时！");
        }
        Order carOrder = new Order();
        carOrder.setId(id);
        carOrder.setIsPay("Y");
        carOrder.setPaymentTime(DateUtils.getNowDate());
        carOrderService.updateCarOrder(carOrder, true);
        return success("支付成功，订单信息已发送至您的手机短信（模拟）");
    }


}
